<template>
  <div
    :class="className"
    :style="{height: height,width: width}"
  />
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'
require('echarts/theme/macarons')

export default {
  name: 'ColumnChart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '530px'
    },
    sumCase: {
      type: Object
    },
    majorCase: {
      type: Object
    },
    parentObject: {
      type: Object
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object
    }
  },
  data() {
    return {
      chart: null,
      parentData: '',
      defaultData: {},
      yAxisLeftName: '每小时数量(件/每小时)',
      isLegendSelected: false
    }
  },
  watch: {
    sumCase: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    majorCase: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    parentObject: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    },
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.parentData = this.sumCase || this.majorCase || this.parentObject
    this.initChart()
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHanlder)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.autoResize) {
      window.removeEventListener('resize', this.__resizeHanlder)
    }
    window.removeEventListener('resize', this.__resizeHanlder)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    setOptions({
      dataName,
      legend,
      series,
      unitNames,
      totalTime,
      totalTimeThisWeek,
      cases,
      validConnections,
      validConnectedCustomers,
      ptp,
      casesThisWeek,
      casesLastWeek,
      validConnectionsThisWeek,
      validConnectionsLastWeek,
      validConnectedCustomersThisWeek,
      validConnectedCustomersLastWeek,
      ptpThisWeek,
      ptpLastWeek
    } = {}) {
      console.warn(legend, series, unitNames, totalTime, cases, validConnections, validConnectedCustomers, ptp)
      const parentBarData = {
        // color: colors,
        tooltip: {
          // show: false,
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          /* formatter: `
                        {b0}<br />
                        {a0}：{c0}<br />
                        {a1}：{c1}<br />
                        {a2}：{c2}<br />
                        {a3}：{c3}<br />
                        {a4}：{c4}<br />
                        {a5}：{c5}<br />
                        {a6}：{c6}<br />
                        {a7}：{c7}<br />
                        {a8}：{c8}<br />
                    ` */
          formatter: function(params, ticket, callback) {
            let arr = []
            arr = legend.data.map((m, i) => {
              let obj = {}
              params.forEach((n, j) => {
                if (n.seriesName === m) {
                  obj = n
                }
              })
              return obj
            })
            // console.log(params, legend.data, arr)
            let str = `${arr[0].name || '---'}<br />`
            arr.forEach((m, i) => {
              if (!m.marker) return false
              str += `${m.marker} ${m.seriesName}：${typeof m.data === 'number' ? m.data : '---'}<br />`
            })
            return str
          }
        },
        toolbox: {
          feature: {
            dataView: {
              show: false,
              readOnly: false
            },
            magicType: {
              show: true,
              title: '',
              type: ['line', 'bar'],
              iconStyle: {
                textPosition: 'top'
              }
            },
            restore: {
              // title: '',
              show: true
            },
            saveAsImage: {
              show: false
            }
          }
        },
        legend: legend || {},
        xAxis: [{
          type: 'category',
          data: unitNames,
          axisPointer: {
            type: 'shadow'
          }
        }],
        yAxis: [{
          type: 'value',
          name: this.yAxisLeftName,
          nameLocation: 'end',
          nameTextStyle: {
            fontSize: 11,
            align: 'left',
            verticalAlign: 'bottom',
            padding: [0, 0, -7, -30],
            lineHeight: 1
            // bottom: -10
          },
          min: 0,
          max: MAXYaxisLeftVal,
          interval: 10
        }, {
          type: 'value',
          name: '有效工作时间（小时）',
          min: 0,
          max: Math.max.apply(Math, totalTime),
          interval: 24,
          nameTextStyle: {
            fontSize: 11,
            padding: [0, 0, -7, 0],
            lineHeight: 10
          },
          axisLabel: {
            // formatter: '{value} °C'
          }
        }],
        series: series || [{
          name: '有效工作时间',
          type: 'bar',
          // barGap: '50%',
          barMaxWidth: 50,
          smooth: false,
          data: totalTime,
          yAxisIndex: 1
        }, {
          name: '每小时处理案件数',
          type: 'line',
          smooth: false,
          data: cases
        }, {
          name: '每小时有效联络次数',
          type: 'line',
          smooth: false,
          data: validConnections
        }, {
          name: '每小时有效联络客户数',
          type: 'line',
          smooth: false,
          data: validConnectedCustomers
        }, {
          name: '每小时PTP数',
          type: 'line',
          smooth: false,
          data: ptp
        }]
      }
      const weekHourArr = [cases, validConnections, validConnectedCustomers, ptp]
      let weekHourLegendKeys = []
      let MAXYaxisLeftVal = 0
      let legendNoTimeSelected = []
      let lastWeekArray = []
      let yAxisLeftNameIndex = 0
      switch (dataName) {
        case 'week-hour':
          if (!this.isLegendSelected) {
            // eslint-disable-next-line
                        MAXYaxisLeftVal = Math.max.apply(Math, [...cases, ...validConnections, ...validConnectedCustomers, ...ptp])
            weekHourLegendKeys = Object.keys(legend.selected)
            weekHourLegendKeys.shift()
            weekHourArr.forEach((m, i) => {
              // eslint-disable-next-line
                            if (Math.max.apply(Math, m) === MAXYaxisLeftVal) {
                this.$nextTick(t => {
                  this.yAxisLeftName = weekHourLegendKeys.filter((m, i) => Object.values(legend.selected)[i])[i]
                  parentBarData.yAxis[0].name = this.yAxisLeftName
                  this.chart.setOption(parentBarData)
                })
              }
            })
          }
          this.chart.on('legendselectchanged', e => {
            this.isLegendSelected = true
            console.log('LEGEND_SELECTED:', e)
            const arr = Object.values(e.selected)
            const arrKeys = Object.keys(e.selected)
            arr.shift()
            arrKeys.shift()
            const arrComputed = arr.map((m, i) => { return { i: i, sel: m, ar: weekHourArr[i] } }).filter((n, j) => n.sel).map(m => m.ar)
            // eslint-disable-next-line
                        legend.selected = e.selected
            MAXYaxisLeftVal = Math.max.apply(Math, arrComputed.reduce((a, b) => [...a, ...b], []))
            arrComputed.forEach((m, i) => {
              if (Math.max.apply(Math, m) === MAXYaxisLeftVal) {
                this.yAxisLeftName = arrKeys.filter((m, i) => arr[i])[i]
              }
            })
            // console.log(arrKeys.filter((m, i) => arr[i]).filter((n, j) => arrComputed[j].includes(n)))
            console.log('arrComputed:', arrComputed, MAXYaxisLeftVal, this.yAxisLeftName)
            this.chart.clear()
            this.chart.setOption(parentBarData)
          })
          break
        case 'last-week-hour':
          totalTime = totalTimeThisWeek
          cases = casesThisWeek
          legendNoTimeSelected = Object.values(legend && legend.selected || {})
          legendNoTimeSelected.shift()
          yAxisLeftNameIndex = legendNoTimeSelected.map((m, i) => { return { m: m, i: i } }).filter((n, j) => n.m)
          this.yAxisLeftName = ['每小时数量(件/每小时)', 0, '有效联络数(次/每小时)', 0, '有效联络客户数(次/每小时)', 0, 'PTP数(件/每小时)'][yAxisLeftNameIndex[0] && yAxisLeftNameIndex[0].i || 0]
          parentBarData.yAxis[0].name = this.yAxisLeftName
          lastWeekArray = [casesThisWeek, casesLastWeek, validConnectionsThisWeek, validConnectionsLastWeek, validConnectedCustomersThisWeek, validConnectedCustomersLastWeek, ptpThisWeek, ptpLastWeek].filter((m, i) => legendNoTimeSelected[i]).reduce((a, b) => [...a, ...b], []) || []
          // eslint-disable-next-line
                    MAXYaxisLeftVal = Math.max.apply(Math, lastWeekArray)
          break
      }
      this.chart.clear()
      this.chart.setOption(parentBarData)
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      const cData = this.chartData || {}
      console.log('this.chartData:', cData, this.chartData)
      this.setOptions(cData)
    },
    setOptions1(obj) {
      // common config
      obj.legend && (obj.legend.selectedMode = false)
      const currColors = location.hash.split('=')[1] && decodeURIComponent(location.hash.split('=')[1]).replace(/\[|\]|\'/img, '').split(',') || ''
      obj.color = currColors || obj.color
      this.chart.setOption(obj)
    },
    initChart1() {
      console.log('parentData:', this.parentData)
      this.chart = echarts.init(this.$el, 'macarons')
      if (this.parentData) {
        this.chart.setOption(this.parentData)
        this.chart.on('finished', arg => {
        })
        return
      }
      // default test data
      this.chart.setOption(this.defaultData)
    }
  }
}
</script>
